//
//  MainViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "MainViewController.h"
#import "OALoginViewController.h"
#import "itemcell.h"
#import "OABaseNavViewController.h"
//#import "ComingworkongController.h"
//#import "emailViewController.h"
//#import "iseditViewController.h"
//#import "overworkingViewController.h"
//#import "comingthingViewController.h"
//#import "ideitworkViewController.h"
//#import "workedViewController.h"
//#import "OANewInViewController.h"
//#import "OANewSendViewController.h"
//#import "NotonewsViewController.h"
//#import "webViewController.h"
//#import "OAAddressViewController.h"
//#import "OASMSViewController.h"
#import "MainViewCell.h"
#import "BaseModel.h"
//#import "ReceieveViewController.h"
#import "AuthHelper.h"
#define kWB_Login_NotificationName @"requestdata"

@interface HomeModel : BaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@end
@implementation HomeModel


@end
@interface MainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SangforSDKDelegate>
@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;
@property(nonatomic,strong)NSMutableArray * contentArray;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *followLayout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//@property (nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong)HomeModel * homeModel;
@property(nonatomic,strong)NSMutableArray * originalData;
@property(nonatomic,strong)NSArray * array;
@property (nonatomic, strong) AuthHelper *helper;
@end

@implementation MainViewController
static NSString * const reuseIdentifier = @"CellIdentifier";
-(NSMutableArray*)contentArray{
    if (_contentArray == nil) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}

- (void)viewDidLoad {
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
    [super viewDidLoad];
        _helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];

    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
}
// 更改标题的颜色

    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:

[UIColor whiteColor],NSForegroundColorAttributeName, nil];
 
[self.navigationController.navigationBar setTitleTextAttributes:attributes];
self.title = @"浙江省贸促会移动办公系统";
 self.navigationController.navigationBar.barTintColor = [UIColor blueColor];
   [self _backbutton];
    //  [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"标题"] forBarMetrics:UIBarMetricsDefault];
   
     self.followLayout.sectionInset = UIEdgeInsetsMake(15+60, 8, 8, 8);
    self.followLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 50 )/ 4 , ([UIScreen mainScreen].bounds.size.width -25 )/ 4);
    self.followLayout.minimumLineSpacing = 10;
// 判断版本
//[self upApp];
//定时器
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(news) userInfo:nil repeats:YES];
        // 开启当前线程
        [[NSRunLoop currentRunLoop] run];
    });

      //修改返回按钮的颜色和字体
  self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
   UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;

}
#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
NSString *userName = @"ccpitzjapp";             //用户名认证的用户名
NSString *password = @"ccpitzjappapp";                //用户名认证的密码


    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
NSString *userName = @"ccpitzjapp";             //用户名认证的用户名
NSString *password = @"ccpitzjappapp";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书

    NSArray *paths = nil;
    switch (authType)
    {
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName];
                NSLog(@"PATH = %@",authPaths);
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
            
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            
            break;
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
               break;
        
//        default:
//            NSLog(@"Other failed!!!");
//            break;
    }
    [self.helper loginVpn:authType];
}

//- (void)upApp{
//if (!([[NSUserDefaults standardUserDefaults]objectForKey:@"version"])) {
//    [[NSUserDefaults standardUserDefaults] setObject:@"1"forKey:@"version"];
//     _array = @[@{@"version":[[NSUserDefaults standardUserDefaults]objectForKey:@"version"]}];
//
//}
//
//else{
//  _array = @[@{@"version":[[NSUserDefaults standardUserDefaults]objectForKey:@"version"]}];
//}
//
//[HttpTools requestWithURL:KExchmain arrays:_array method:@"updateDown" success:^(id JSON) {
//         NSArray *tempArray  = JSON[@"data"];
//        NSDictionary * dict = [tempArray firstObject];
//    if ([[dict objectForKey:@"result"] isEqualToString:@"0"])
//     {
//     NSString * n = [[NSUserDefaults standardUserDefaults]objectForKey:@"version"];
//     int intString = [n intValue]+1;
//NSString *stringInt = [NSString stringWithFormat:@"%d",intString];
//     
//    [[NSUserDefaults standardUserDefaults] setObject:stringInt forKey:@"version"];
//    [self.view makeToast:@"版本需要更新"];
//}
//
//    }failure:^(NSError *error) {
//        
//    }];
//
//    
//
//}

- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWB_Login_NotificationName object:nil];
    }
// 使用storyboard创建的控制调用的初始化方法
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(news) name:kWB_Login_NotificationName object:nil];
       
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
  [self news];
//临时放在此处
//[self setupSubView];

}

- (void)news{
 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
 
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
                    [self setupSubView];

            [self.collectionView reloadData];

    } failure:^(NSError *error) {
        
    }];
  
  [HttpTools requestWithURL:@"http://192.168.100.15:8080/MDAndroidOA/jh/exchmain" arrays:array method:@"homeBigPqwoiunu" success:^(id JSON) {
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
    _dic = dict;
      
            [self.collectionView reloadData];

    } failure:^(NSError *error) {
        
    }];
    
    


}
-(void)setupSubView{
    if ([[_dic objectForKey:@"whetherExchange"] isEqualToString:@"0"]) {
          NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList1" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];    }
    
  else {
         NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];    }
    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contentArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MainViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;

if ([dict[@"title"] isEqualToString:@"待办公文"]) {
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
    else if ([dict[@"title"]isEqualToString:@"公文收发"]) {
        [cell.btnCount setTitle:_dic[@"exchange"] forState:UIControlStateNormal];
        if( [_dic[@"exchange"] isEqualToString:@"0"]) {
            cell.btnCount.hidden = YES;
        }else{
            cell.btnCount.hidden = NO;
        }
        
    }
    else if ([dict[@"title"]isEqualToString:@"待办事项"]) {
        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        if ([self.homeModel.read integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    
    else if ([dict[@"title"] isEqualToString:@"电子邮件"]) {
        [cell.btnCount setTitle:self.homeModel.mail forState:UIControlStateNormal];
        if ([self.homeModel.mail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }
    [cell layoutIfNeeded];
    return cell;

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// NSLog(@"cell #%ld was selected", (long)indexPath.row);
 NSDictionary * dict =  self.contentArray[indexPath.item];
  
   

//    int ssl_vpn_logout();



         }


- (void)_initViews{
//float width = kScreenWidth/4-10;
//UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
//flowlayout.itemSize = CGSizeMake(width, width*3/2);
//
//flowlayout.minimumInteritemSpacing = 5;
//flowlayout.minimumLineSpacing = 5;
// _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,90, kScreenWidth, KScreenHeight) collectionViewLayout:flowlayout];
//    _collectionView.delegate = self;
//    _collectionView.dataSource = self;
//    _collectionView.backgroundColor = [UIColor clearColor];
//   // _collectionView.backgroundView = nil;
//    //_collectionView.backgroundColor = [UIColor yellowColor];
//     [_collectionView registerClass :[itemcell class]forCellWithReuseIdentifier:@"itemcellid"];
//    [self.view addSubview:_collectionView];
 
    
    self.followLayout.sectionInset = UIEdgeInsetsMake(15+70, 8, 8, 8);
    self.followLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 50 )/ 4 , ([UIScreen mainScreen].bounds.size.width - 50 )/ 4);
    self.followLayout.minimumLineSpacing = 10;



}


- (void)_backbutton{
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame = CGRectMake(0, 0, 44, 44);
                [rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                    [rightButton setTitle:@"退出" forState:UIControlStateNormal];
                    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                 
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    UIButton *liftButton = [UIButton buttonWithType:UIButtonTypeCustom];
liftButton.frame = CGRectMake(0, 0,95*.6, 72*.6);
[liftButton setImage:[UIImage imageNamed:@"标题logo"] forState:UIControlStateDisabled];
 self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:liftButton];
 liftButton.enabled = NO;

    
    
}

- (void)rightButtonAction:(UIButton *)button {

 UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"是否退出登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 1)
//    {
//    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"auto"];
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"remember"])
//    {
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"remember"];
//    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"userId"];
//    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"pwdId"];
//    }
//          // [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:@"remember"];
//
//       OALoginViewController * loginVC = (OALoginViewController*) [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
//        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
//        self.view.window.rootViewController = nav;
//        nav.navigationBar.hidden = YES;
//    }
if (buttonIndex == 1){
 [_helper logoutVpn];
 OALoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
     [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
    self.view.window.rootViewController = loginVC;


}
}
@end
